package com.itheima.mp.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.UserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void deleteBalanceById(Long id, Integer money) {
        User user = this.getById(id);

        if(user == null){
            throw new RuntimeException("用户为空");
        }

        if(user.getBalance() < money){
            throw new RuntimeException("余额不足");
        }

        //baseMapper.deleteBalanceById(money, id);
        Integer remain = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remain)
                .set(remain == 0, User::getStatus, 2)
                .eq(User::getId, user.getId()) // 乐观锁
                .update();
    }

    @Override
    public List<UserVO> QueryUsers(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Integer minBalance = userQuery.getMinBalance();
        Integer maxBalance = userQuery.getMaxBalance();

        List<User> userList = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list(); // on 是查一个， page 是分页查询

        return BeanUtil.copyToList(userList, UserVO.class);
    }
}
